<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleAdd" :form="form">
        <a-form-item
          label="添加模式"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-tag color="#428bca" @click="checkMode()" v-if="!this.check">切换为扫码模式</a-tag>
          <a-tag color="#428bca" @click="checkMode()" v-else>切换为选择模式</a-tag>
        </a-form-item>
        <a-form-item
          label="商品"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
          v-if="!this.check"
        >
          <a-select v-decorator="['goodId',{ rules: [{ required: true, message: '请选择' }] }]" show-search placeholder="请选择" >
            <a-select-option :value="i.id" v-for="i in this.prodOption" :key="i.value">{{ i.goodName }} {{ i.phoneCode1 }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="串码"
          v-else
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            v-decorator="['phoneCodeList', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="返厂商品清单">
      <a-table ref="table" size="default" rowKey="key" :columns="columns" :data-source="loadData">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="form1">
        <a-form-item
          label="返厂日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['orderDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" style="width: 100%" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" name="memo" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交返厂</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>
  
<script>
import { getPageBySingleCodeUsingGET } from '@/api/api/kucunguanli.ts'
import { addReturnsUsingPOST } from '@/api/api/caigouguanli.ts'
import moment from 'moment'
export default {
  name: 'ReturnFactoryOutStoreDetail',
  data() {
    return {
      check: false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      toDays: moment().format('YYYY-MM-DD'),
      prodOption: [],
      queryParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      form: this.$form.createForm(this),
      form1: this.$form.createForm(this),
      columns: [
        {
          title: '商品',
          dataIndex: 'goodName',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
    }
  },
  created() {
    this.handleProd()
  },
  methods: {
    handleProd() {
      getPageBySingleCodeUsingGET({
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date,
        storeId: this.$route.params.storeId,
        supplyId: this.$route.params.supplyId,
      })
        .then((res) => {
          this.prodOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    // handler
    checkMode() {
      this.check = !this.check
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    handleDel(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loadData.splice(
            that.loadData.findIndex((item) => item.id === record.id),
            1
          )
          // this.loadData = this.loadData
        },
      })
    },
    handleAdd(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.check) {
            getPageBySingleCodeUsingGET({
              phoneCodeList: this.removeTrim(values.phoneCodeList.split('\n')).toString(),
              status: 1,
              ...this.$route.query,
            })
              .then((res) => {
                const data = res.data.list.map((item, index) => {
                  return {
                    inventoryId:item.id,
                    ...item,
                  }
                })
                const includes = this.loadData.some((i) => data?.map((j) => j.phoneCode1)?.includes(i.phoneCode1))
                if (!!includes) {
                  this.$message.error('存在相同串码')
                } else {
                  this.loadData = this.loadData.concat(data)
                }
              })
              .catch((error) => {
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            const includes = this.loadData
              .map((item) => item.phoneCode1)
              .includes(
                this.prodOption.find((item) => {
                return item.id == values.goodId
              }).phoneCode1
              )
            if (!!includes) {
              this.$message.error('存在相同串码')
              return false
            }
            this.loadData.push({
              ...values,
              inventoryId: this.prodOption.find((item) => {
                return item.id == values.goodId
              }).id,
              inDate: this.prodOption.find((item) => {
                return item.id == values.goodId
              }).inDate,
              phoneCode1: this.prodOption.find((item) => {
                return item.id == values.goodId
              }).phoneCode1,
              goodName: this.prodOption.find((item) => {
                return item.id == values.goodId
              }).goodName,
              goodId: this.prodOption.find((item) => {
                return item.id == values.goodId
              }).goodId,
            })
          }
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form1.validateFields((err, values) => {
        if (!err) {
          if(this.loadData.length == 0) {
            this.$message.error('没有可返厂退库的商品')
            return false
          }
          const params = {
            returnsListParamList: this.loadData.map((item) => {
              return {
                ...item
              }
            }),
            memo: values.memo,
            orderDate: values.orderDate,
            storeId: this.$route.params.storeId,
            supplyId: this.$route.params.supplyId,
            retType: 0,
          }
          addReturnsUsingPOST({ ...params })
            .then((res) => {
              this.$message.success('操作成功')
              this.$router.push({ path: `/purchasing/returnFactoryShopRecord/detail/${res.data.id}` })
            })
            .catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
}
</script>